package com.yyk.yiliao.util.rx;

import android.os.Build;
import android.util.Log;
import android.webkit.WebSettings;

import com.yyk.yiliao.config.MyApplication;

import java.io.IOException;
import java.util.Collections;
import java.util.concurrent.TimeUnit;

import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Protocol;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * Created by Administrator on 2018/6/14 0014.

 * 这个 管理类 是为了 对 RxZkUtils 进行初始化的操作  这是  r 1.x 不是 2.x
 *
 */

public class RxUtils {
    private ApiService apiService;
    public final Retrofit retrofit;
    private static final int READ_TIMEOUT = 60;//读取超时时间,单位  秒
    private static final int WRITE_TIMEOUT = 60;//写入超时时间,单位  秒
    private static final int CONN_TIMEOUT = 12;//连接超时时间,单位  秒

    //恶汉式
    private static class RxManger {
        private volatile static RxUtils INSTANCE = new RxUtils();
    }


    private static String getUserAgent() {
        String userAgent = "";
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
            try {
                userAgent = WebSettings.getDefaultUserAgent(MyApplication.getInstance());
            } catch (Exception e) {
                userAgent = System.getProperty("http.agent");
            }
        } else {
            userAgent = System.getProperty("http.agent");
        }
        StringBuffer sb = new StringBuffer();
        for (int i = 0, length = userAgent.length(); i < length; i++) {
            char c = userAgent.charAt(i);
            if (c <= '\u001f' || c >= '\u007f') {
                sb.append(String.format("\\u%04x", (int) c));
            } else {
                sb.append(c);
            }
        }
        return sb.toString();
    }


    private class TestInterceptor implements Interceptor {
        private final String TAG = "jsonData";

        @Override
        public Response intercept(Chain chain) throws IOException {
            Request original = chain.request();
            Response response = chain.proceed(original);
            ResponseBody responsePeekBody = response.peekBody(1024 * 1024);
//            Log.i(TAG, "intercept: " + responsePeekBody.string());
            return response;
        }
    }


    //私有化构造器
    private RxUtils() {


        OkHttpClient client = new OkHttpClient.Builder()//初始化一个client,不然retrofit会自己默认添加一个
                .addInterceptor(new Interceptor() {
                    @Override
                    public Response intercept(Chain chain) throws IOException {
                        Request request = chain.request().newBuilder().removeHeader("User-Agent")
                                //移除旧的
                                .addHeader("User-Agent", getUserAgent())
                                //添加真正的头部
                                .build();
                        return chain.proceed(request);


                    }
                })
                .connectTimeout(CONN_TIMEOUT, TimeUnit.SECONDS)//设置连接时间为12s
                .writeTimeout(WRITE_TIMEOUT, TimeUnit.SECONDS)
                .readTimeout(READ_TIMEOUT, TimeUnit.SECONDS)
//                .addInterceptor(new TestInterceptor())
                .protocols(Collections.singletonList(Protocol.HTTP_1_1))  //解决  W/System.err: okhttp3.internal.http2.StreamResetException: stream was reset: CANCEL
                .build();//设置读取时间为一分钟


        //创建Retrofit
        retrofit = new Retrofit.Builder()
                .client(client)//添加一个client,不然retrofit会自己默认添加一个
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .addConverterFactory(GsonConverterFactory.create())
                .baseUrl(ApiService.BASE_URL + "/")
                .build();
        //可以添加拦截器等等。。。。。
        //        apiService = retrofit.create(ApiService.class);

    }

    /*
    获取实列
     */
    public static RxUtils getInstance() {

        return RxManger.INSTANCE;
    }


}
